<script lang="ts" setup>
import {
  ChevronsUpDown,
} from 'lucide-vue-next';

import { useSidebar } from '@/components/ui/sidebar';

import { useAppStore } from '@/stores/app';
import type { AppInfo } from '@/stores/app';

const appStore = useAppStore();

const { isMobile, open } = useSidebar();

const activeApp = ref<AppInfo | undefined>(appStore.currentApp);

const availableApps = computed(() => appStore.apps.filter(app => !app.disabled));
const disabledApps = computed(() => appStore.apps.filter(app => app.disabled));

function setActiveApp(app: AppInfo) {
  activeApp.value = app;
  appStore.setAppKey(app.key);
}
</script>

<template>
  <SidebarHeader>
    <SidebarMenu>
      <SidebarMenuItem>
        <DropdownMenu>
          <DropdownMenuTrigger as-child>
            <SidebarMenuButton
              size="lg"
              class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
            >
              <div class="flex items-center justify-center rounded-lg aspect-square size-8 bg-sidebar-primary text-sidebar-primary-foreground">
                <component :is="activeApp?.logo" class="size-4" />
              </div>
              <div class="grid flex-1 text-sm leading-tight text-left">
                <span class="font-semibold truncate">{{ activeApp?.name }}</span>
                <span class="text-xs truncate">{{ activeApp?.description }}</span>
              </div>
              <ChevronsUpDown class="ml-auto" />
            </SidebarMenuButton>
          </DropdownMenuTrigger>

          <DropdownMenuContent
            class="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
            align="start"
            :side="isMobile || open ? 'bottom' : 'right'"
            :side-offset="4"
          >
            <DropdownMenuLabel class="text-xs text-muted-foreground">
              产品列表
            </DropdownMenuLabel>

            <DropdownMenuItem
              v-for="(app) of availableApps"
              :key="app.key"
              class="gap-2 p-2"
              @click="setActiveApp(app)"
            >
              <div class="flex items-center justify-center border rounded-sm size-6">
                <component :is="app.logo" class="size-4 shrink-0" />
              </div>
              {{ app.name }}
            </DropdownMenuItem>

            <DropdownMenuSeparator />

            <DropdownMenuItem
              v-for="(app) of disabledApps"
              :key="app.key"
              class="gap-2 p-2"
              disabled
              @click="setActiveApp(app)"
            >
              <div class="flex items-center justify-center border rounded-sm size-6">
                <component :is="app.logo" class="size-4 shrink-0" />
              </div>
              {{ app.name }}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </SidebarMenuItem>
    </SidebarMenu>
  </SidebarHeader>
</template>
